package fun.tan90.device.protocol;

import org.noear.liquor.eval.CodeSpec;
import org.noear.liquor.eval.Maps;
import org.noear.liquor.eval.ParamSpec;
import org.noear.liquor.eval.Scripts;
import org.noear.snack.ONode;

import java.util.List;

public class LiquorDemo {

    public static void main(String[] args) throws Exception {
        CodeSpec codeSpec = new CodeSpec("""
                import cn.hutool.core.util.HexUtil;
                import java.nio.ByteBuffer;
                import java.util.ArrayList;
                import java.util.List;
                import java.util.Map;
                
                
                 class TLVDecoder {
                
                    public String bytesToHex(byte[] bytes) {
                        char[] hexChars = new char[bytes.length * 2];
                        for (int i = 0; i < bytes.length; i++) {
                            int v = bytes[i] & 0xFF; // 将byte转为无符号整数
                            hexChars[i * 2] = "0123456789ABCDEF".charAt(v >>> 4); // 高4位
                            hexChars[i * 2 + 1] = "0123456789ABCDEF".charAt(v & 0x0F); // 低4位
                        }
                        return new String(hexChars);
                    }
                
                    /**
                     * TLV解码器（假设T和L各占2字节，大端序）
                     *
                     * @param data 输入的字节数组
                     * @return 解码后的TLV对象列表
                     * @throws IllegalArgumentException 数据不完整或格式错误
                     */
                    public List<Map<String, Object>> decode(byte[] data) {
                        List<Map<String, Object>> entries = new ArrayList<>();
                        ByteBuffer buffer = ByteBuffer.wrap(data);
                        buffer.order(java.nio.ByteOrder.BIG_ENDIAN); // 大端序（高位在前）
                        while (buffer.remaining() >= 4) { // 至少需要4字节（T+L）
                            // 1. 解析Type（2字节）
                            int type = buffer.getShort() & 0xFFFF; // 转为无符号整数
                
                            // 2. 解析Length（2字节）
                            int length = buffer.getShort() & 0xFFFF; // 转为无符号整数
                
                            // 检查剩余数据是否足够
                            if (buffer.remaining() < length) {
                                throw new IllegalArgumentException("数据不完整: 期望长度 " + length + "，实际剩余 " + buffer.remaining());
                            }
                
                            // 3. 提取Value
                            byte[] value = new byte[length];
                            buffer.get(value);
                            entries.add(Map.of("key", String.format("%04X", type), "length", length, "value", HexUtil.encodeHexStr(value, false)));
                        }
                        return entries;
                    }
                }
                return new TLVDecoder().decode(HexUtil.decodeHex(data));
                """)
//                .imports("cn.hutool.core.util.HexUtil")
                .parameters(new ParamSpec("data", String.class)) //申明参数
                .returnType(List.class); //申明返回类型

        String tlvStr = "02B20002000102B40002001502B60004B46B6D6602DA0002075B035C00020258035E0002000A036000020000036C00020000037000020000037200020000037400020000037600020000037800080000000000000000038000080000000000000000038A00080000000000000000039200080000000000000000039A0008000000000000000003A20002000003A40008000000000000000003AC0002000003AE000600000000000003B40002000003B60008000000000000000003BE0002000003C0000600000000000003C60002000003C80008000000000000000003D00002000003D2000600000000000003D80002000003DA0008000000000000000003E20002000003E4000600000000000003EA0002000003EC0008000000000000000003F40002000003F6000600000000000003FC00020000";
        Object obj = Scripts.eval(codeSpec, Maps.of("data", tlvStr));
        System.out.println(ONode.load(obj).toJson());
    }
}
